package com.gogowan.agroenterprise.supply;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.model.CommodityInfo;
import com.gogowan.agroenterprise.model.CommodityResultInfo;
import com.gogowan.agroenterprise.model.SellInfo;
import com.gogowan.agroenterprise.supply.utils.Files;
import com.gogowan.agroenterprise.supply.utils.Net;
import com.gogowan.agroenterprise.utils.Utils;

public class CommodityDetailActivity extends BaseActivity{
	
	private TextView title;
	private TextView productName;
	private TextView depositeRate;
	private TextView price;
	private TextView measurement;
	//private TextView startingDate;
	//private TextView deadline;
	//private TextView status;
	//private LinearLayout statusLL;
	private TextView productNature;
	private TextView productDetail;
	private Gallery gallery;
	private LinearLayout galleryLinear;
	private Button orderBtn;
	
	private CommodityInfo commodityInfo;
	private String commodityDetail;
	
	public static HashMap<String, Bitmap> imagesCache = new HashMap<String, Bitmap>(); // 图片缓存
	public static ImageAdapter imageAdapter;
	private int num = 0;
	List<String> urls = new ArrayList<String>(); // 所有图片地址List

	List<String> url = new ArrayList<String>(); // 需要下载图片的url地址
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_commodity);
		
		title = (TextView)findViewById(R.id.commodity_title);
		productName = (TextView)findViewById(R.id.commodity_product_name);
		depositeRate = (TextView)findViewById(R.id.commodity_deposit_rate);
		price = (TextView)findViewById(R.id.commodity_price);
		measurement = (TextView)findViewById(R.id.commodity_measurement);
		//startingDate = (TextView)findViewById(R.id.commodity_starting_date);
		//deadline = (TextView)findViewById(R.id.commodity_deadline);
		//status = (TextView)findViewById(R.id.commodity_status);
		//statusLL = (LinearLayout)findViewById(R.id.commodity_status_ll);
		productNature = (TextView)findViewById(R.id.commodity_product_nature);
		productDetail = (TextView)findViewById(R.id.commodity_detail);
		orderBtn = (Button)findViewById(R.id.commodity_order);
		gallery = (Gallery)findViewById(R.id.commodity_gallery);
		galleryLinear = (LinearLayout)findViewById(R.id.commodity_gallerylinear);
		
		Intent intent = getIntent();
		commodityDetail = intent.getStringExtra("CommodityDetail");
		
		
		if (commodityDetail == null || commodityDetail.equals("")) {
			showFinishDialog("警告", "数据请求失败");
		} else {
			CommodityResultInfo commodityResultInfo = (CommodityResultInfo)Utils.fromJSON(commodityDetail, CommodityResultInfo.class);
			commodityInfo = commodityResultInfo.getCommodityInfo();
			if (commodityInfo == null) {
				showFinishDialog("警告", "数据请求失败");
			} else {
				
				String titleString = commodityInfo.getCommodityName();
				float depositeRatefloat = commodityInfo.getRate();
				float pricefloat = commodityInfo.getPrice_One();
				//int statusInt = commodityInfo.getStatus();
				String measurementString = commodityInfo.getUnit();
				//String startingDateString = commodityInfo.getTimeUp();
				//String deadlineString = commodityInfo.getTimeDown();
				String detailString = commodityInfo.getCommodityDesc();
				
				if (titleString == null || titleString.equals("")) {
					showFinishDialog("警告", "数据请求失败");
				} else {
					title.setText(titleString);
					productName.setText(titleString);

					/*if (statusInt == 0) {
						statusLL.setVisibility(View.VISIBLE);
						orderBtn.setEnabled(false);
					}*/

					if (depositeRatefloat == 0) {
						depositeRate.setText("");
					} else {
						depositeRate.setText(String.valueOf(depositeRatefloat));

						if (pricefloat == 0) {
							price.setText("");
						} else {
							price.setText(String.valueOf(pricefloat));

							if (measurementString == null || measurementString.equals("")) {
								measurement.setText("");
							} else {
								measurement.setText(measurementString);
								
								if (detailString == null || detailString.equals("")) {
									productDetail.setText("");
								} else {
									productDetail.setText(detailString);
								}
								/*if (startingDateString == null
										|| startingDateString.equals("")) {
									startingDate.setText("");
								} else {
									startingDate.setText(startingDateString);

									if (deadlineString == null
											|| deadlineString.equals("")) {
										deadline.setText("");
									} else {
										deadline.setText(deadlineString);

									}
								}*/
							}
						}
					}
				}
					
				// 拼接属性列表
				List<SellInfo> sellInfos = commodityInfo.getSellList();
				if (sellInfos == null || sellInfos.size() == 0) {
					productNature.setText("");
				} else {
					StringBuffer sb = new StringBuffer();
					for (int i = 0; i < sellInfos.size(); i++) {
						sb.append(sellInfos.get(i).getPropertyName()).append(":").append(sellInfos.get(i).getPropertyValue()).append("\n");
					}
					productNature.setText(sb);
				}
			}
			
			//如果显示图片的话 在这写
			Files.mkdir(this);
			
			
			if (commodityInfo.getPhotoList() == null || commodityInfo.getPhotoList().size() == 0) {
				galleryLinear.setVisibility(View.GONE);
			} else {
				Bitmap image = BitmapFactory.decodeResource(getResources(),
						R.drawable.background_main);
				imagesCache.put("background_non_load", image); // 设置缓存中默认的图片
				
				for (int i = 0; i < commodityInfo.getPhotoList().size(); i++) {
					urls.add(commodityInfo.getPhotoList().get(i).getPhotoPathNormal());
				}
				
				imageAdapter = new ImageAdapter(urls, this);
				gallery.setAdapter(imageAdapter);
				
				gallery.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						
					}
				});
				
				gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						num = arg2;
						Log.i("mahua", "ItemSelected==" + arg2);
						GalleryWhetherStop();
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});
			}
		
			
			orderBtn.setOnClickListener(orderBtnCallback);
		}
	}
	
	/**
	 * 下订单按钮点击事件
	 */
	public Button.OnClickListener orderBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			
			
			Intent intent = new Intent(CommodityDetailActivity.this,OrderUserInfoActivity.class);
			intent.putExtra("commodityDetail", commodityDetail);
			startActivity(intent);
			Utils.randomAnim(CommodityDetailActivity.this);
		}
		
	};
	/**
	 * finish本页面
	 * @param s
	 * @param string
	 */
	private void showFinishDialog(String s,String string){
    	new AlertDialog.Builder(CommodityDetailActivity.this).setTitle(s)
		.setMessage(string).setPositiveButton("确定", new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				CommodityDetailActivity.this.finish();
				Utils.randomAnim(CommodityDetailActivity.this);
			}
		}).create().show();
    }
	
	/**
	 * 判断Gallery滚动是否停止,如果停止则加载当前页面的图片
	 */
	private void GalleryWhetherStop() {
		Runnable runnable = new Runnable() {
			public void run() {
				try {
					int index = 0;
					index = num;
					Thread.sleep(1000);
					if (index == num) {
						url.add(urls.get(num));
						if (num != 0 && urls.get(num - 1) != null) {
							url.add(urls.get(num - 1));
						}
						if (num != urls.size() - 1 && urls.get(num + 1) != null) {
							url.add(urls.get(num + 1));
						}
						android.os.Message m = new android.os.Message();
						m.what = 1;
						mHandler.sendMessage(m);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}

	// 加载图片的异步任务
	class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			try {
				String url = params[0];
				boolean isExists = Files.compare(url);
				if (isExists == false) {
					Net net = new Net();
					byte[] data = net.downloadResource(CommodityDetailActivity.this, url);
					bitmap = BitmapFactory
							.decodeByteArray(data, 0, data.length);
					imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中
					Files.saveImage(url, data);
				} else {
					byte[] data = Files.readImage(url);
					bitmap = BitmapFactory
							.decodeByteArray(data, 0, data.length);
					imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中
				}

				android.os.Message m = new android.os.Message();
				m.what = 0;
				mHandler.sendMessage(m);

			} catch (Exception e) {
				e.printStackTrace();
			}
			return bitmap;
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			try {
				switch (msg.what) {
				case 0: {
					imageAdapter.notifyDataSetChanged();
					break;
				}
				case 1: {
					for (int i = 0; i < url.size(); i++) {
						LoadImageTask task = new LoadImageTask();// 异步加载图片
						task.execute(url.get(i));
						Log.i("mahua", url.get(i));
					}
					url.clear();
				}
				}
				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	public class ImageAdapter extends BaseAdapter {
		public final BaseAdapter Adapter = null;
		private List<String> imageUrls; // 图片地址list
		private Context context;
		int mGalleryItemBackground;

		public ImageAdapter(List<String> imageUrls, Context context) {
			this.imageUrls = imageUrls;
			this.context = context;
			// /*
			// * 使用在res/values/attrs.xml中的<declare-styleable>定义 的Gallery属性.
			// */
			TypedArray a = context.obtainStyledAttributes(R.styleable.Gallery1);
			/* 取得Gallery属性的Index id */
			mGalleryItemBackground = a.getResourceId(
					R.styleable.Gallery1_android_galleryItemBackground, 0);
			/* 让对象的styleable属性能够反复使用 */
			a.recycle();
		}

		public int getCount() {
			return imageUrls.size();
		}

		public Object getItem(int position) {
			return imageUrls.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			Bitmap image;
			ImageView view = new ImageView(context);
			image = imagesCache.get(imageUrls.get(position));
			// 从缓存中读取图片
			if (image == null) {
				image = imagesCache.get("background_non_load");
			}
			// 设置所有图片的资源地址
			view.setImageBitmap(image);
			view.setScaleType(ImageView.ScaleType.FIT_XY);
			view.setLayoutParams(new Gallery.LayoutParams(240, 320));
			view.setBackgroundResource(mGalleryItemBackground);
			/* 设置Gallery背景图 */
			return view;
		}
	}
}
